package com.example.assignment01_javaee.Controller;

import com.example.assignment01_javaee.Entity.User;
import com.example.assignment01_javaee.Service.UserService;
import com.example.assignment01_javaee.Utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public User login(User user){
        String username = user.getUsername();
        String password = user.getPassword();
        User user1 = userService.login(username,password);
        if (user1==null){
            return null;
        }else{
            user.setUsertoken(JwtUtil.createToken());
            return user;
        }
    }

    //注册操作
    @PostMapping("/register")
    public String register(@RequestBody User user){
        userService.register(user);
        return "注册成功";
    }

    //测试未登陆拦截页面
//    @RequestMapping("/welcome")
//    public String welcome(){
//        return "welcome";
//    }

    //退出登录
//    @RequestMapping("/outUser")
//    public void outUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        request.getHeader("token");
//        response.sendRedirect("/toIndex");
//    }
}
